package cn.steel.service.impl;

import cn.steel.domain.entity.SupplierAudit;
import cn.steel.domain.entity.SupplierInfo;
import cn.steel.mapper.SupplierAuditMapper;
import cn.steel.mapper.SupplierInfoMapper;
import cn.steel.service.SupplierAuditService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Slf4j
@Service
@RequiredArgsConstructor
public class SupplierAuditServiceImpl implements SupplierAuditService {

    private final SupplierAuditMapper auditMapper;
    private final SupplierInfoMapper supplierInfoMapper;

    @Override
    @Transactional
    public void submitAudit(Long auditorId, SupplierAudit audit) {
        audit.setAuditorId(auditorId);
        audit.setAuditTime(LocalDateTime.now());

        SupplierAudit existing = auditMapper.findBySupplierId(audit.getSupplierId());
        if (existing == null) {
            audit.setCreateTime(LocalDateTime.now());
            auditMapper.insertAudit(audit);
        } else {
            audit.setId(existing.getId());
            auditMapper.updateAudit(audit);
        }

        // 同步 supplier_info 的审核状态
        SupplierInfo supplierInfo = supplierInfoMapper.findByUserId(audit.getSupplierId());
        if (supplierInfo != null) {
            supplierInfo.setAuditStatus(audit.getStatus());
            supplierInfoMapper.updateSupplierInfo(supplierInfo);
        }

        log.info("供应商资质审核提交成功: supplierId={}", audit.getSupplierId());
    }

    @Override
    public SupplierAudit getAuditBySupplierId(Long supplierId) {
        return auditMapper.findBySupplierId(supplierId);
    }
}